package com.rzjm.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.api.dao.*;
import com.rzjm.api.entity.*;
import com.rzjm.api.exception.TransactionalException;
import com.rzjm.api.service.*;
import com.rzjm.api.util.DateUtil;
import com.rzjm.api.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.security.acl.Group;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class FireWorkServiceImpl extends BaseServiceImpl<FireWorkDao, FireWork> implements FireWorkService {

    @Resource
    private FireWorkDao fireWorkDao;
    @Resource
    private FireWorkUserDao fireWorkUseDao;
    @Resource
    private FireSafetyMeasuresDao safetyMeasuresDao;
    @Resource
    private FireWorkMeasuresDao fireWorkMeasuresDao;
    @Resource
    private SysUserDao sysUserDao;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private UserDao userDao;
    @Resource
    private UserService userService;
    @Resource
    private ShopDao shopDao;
    @Resource
    private WxTemplateService wxTemplateService;
    @Resource
    private GroupsService groupsService;
    @Resource
    private PianqusService pianqusService;

    @Override
    @Transactional
    public int addWorkRecord(FireWork fireWork, String outWorkers, String workerList) {
        int ret = 0;
        try{
            List<Integer> wxWorkerUserId = new ArrayList<>();

            QueryWrapper<FireWork> qwCount = new QueryWrapper<>();
            qwCount.between("create_time", DateUtil.getDay() + " 00:00:00", DateUtil.getDay() + " 23:59:59");
            long todayCount = fireWorkDao.selectCount(qwCount);
            String recordNo = DateUtil.getDays() + StringUtil.LeftBuCode(todayCount+"",3);
            fireWork.setRecordNo(recordNo);
            fireWork.setCreateTime(new Date());
            fireWork.setSafeOpState(0);
            fireWork.setHeaderOpState(0);
            fireWork.setSafeWxUseId(0);
            fireWork.setIsUse(0);

            Department safeDept = departmentService.getSafeDepart(fireWork.getRegCompanyId());
            if(safeDept != null){
//                QueryWrapper<SysUser> qw = new QueryWrapper<>();
//                qw.eq("shop_id", fireWork.getRegCompanyId());
//                qw.eq("dept_id", safeDept.getId());
//                qw.eq("status", 1);
//                qw.last("limit 1");
                SysUser safeUser = sysUserDao.selectById(fireWork.getSafeSysUserId());
                if(safeUser != null){
                    fireWork.setSafeUserName(safeUser.getName());
//                    fireWork.setSafeSysUserId(safeUser.getUserId());
                    fireWork.setCheckAcceptSysUserId(safeUser.getUserId());

                    QueryWrapper<User> qwUser = new QueryWrapper<>();
                    qwUser.eq("sys_user_id", safeUser.getUserId());
                    qwUser.eq("platform", "cy");
                    qwUser.last("limit 1");
                    User user = userDao.selectOne(qwUser);
                    if(user != null){
                        fireWork.setSafeWxUseId(user.getId());
                        fireWork.setCheckAcceptWxUserId(user.getId());
                    }
                }
            }

            Shop shop = shopDao.selectById(fireWork.getRegCompanyId());
            if(shop != null){

                fireWork.setPianquId(shop.getPianquId());
                Groups groups = groupsService.getGroupByPianquId(shop.getPianquId());
                if(groups!= null){
                    fireWork.setGroupId(groups.getId());
                }

                //作业证的类型 0 - 动火作业证  1 - 密闭作业证  2 - 高空作业证
//                if(fireWork.getRecordType() == 0){
//                    //动火责任人
//                    fireWork.setHeaderSysUserId(shop.getFireCheckSysUserId());
//                    SysUser headerUser = sysUserDao.selectById(shop.getFireCheckSysUserId());
//                    if(headerUser != null){
//                        fireWork.setRecordHeaderUser(headerUser.getName());
//                    }
//
//                    QueryWrapper<User> qwUser = new QueryWrapper<>();
//                    qwUser.eq("sys_user_id", shop.getFireCheckSysUserId());
//                    qwUser.eq("platform", "cy");
//                    qwUser.last("limit 1");
//                    User user = userDao.selectOne(qwUser);
//                    if(user!= null){
//                        fireWork.setHeaderWxUserId(user.getId());
//                    }
//
//                } else if(fireWork.getRecordType() == 1){
//                    //密闭责任人
//                    fireWork.setHeaderSysUserId(shop.getSpaceCheckSysUserId());
//                    SysUser headerUser = sysUserDao.selectById(shop.getSpaceCheckSysUserId());
//                    if(headerUser != null){
//                        fireWork.setRecordHeaderUser(headerUser.getName());
//                    }
//
//                    QueryWrapper<User> qwUser = new QueryWrapper<>();
//                    qwUser.eq("sys_user_id", shop.getSpaceCheckSysUserId());
//                    qwUser.eq("platform", "cy");
//                    qwUser.last("limit 1");
//                    User user = userDao.selectOne(qwUser);
//                    if(user != null){
//                        fireWork.setHeaderWxUserId(user.getId());
//                    }
//                } else if(fireWork.getRecordType() == 2){
//                    //高空责任人
//                    fireWork.setHeaderSysUserId(shop.getHighCheckSysUserId());
//                    SysUser headerUser = sysUserDao.selectById(shop.getHighCheckSysUserId());
//                    if(headerUser != null){
//                        fireWork.setRecordHeaderUser(headerUser.getName());
//                    }
//
//                    QueryWrapper<User> qwUser = new QueryWrapper<>();
//                    qwUser.eq("sys_user_id", shop.getHighCheckSysUserId());
//                    qwUser.eq("platform", "cy");
//                    qwUser.last("limit 1");
//                    User user = userDao.selectOne(qwUser);
//                    if(user!= null){
//                        fireWork.setHeaderWxUserId(user.getId());
//                    }
//                }
                //最后审核人员
                fireWork.setLastCheckSysUserId(shop.getFireChargeSysUserId());
                fireWork.setLastCheckState(0);

                // 高空作业票
                if(fireWork.getRecordType() == 2 || fireWork.getRecordType() == 1){
                    // 后台配置的生产经理
                    fireWork.setLastSubmitSysUserId(shop.getFireChargeSysUserId());

                    SysUser sysUser = sysUserDao.selectById(shop.getFireChargeSysUserId());
                    if(sysUser != null){
                        fireWork.setLastSubmitUserName(sysUser.getName());

                        QueryWrapper<User> qwUser = new QueryWrapper<>();
                        qwUser.eq("sys_user_id", shop.getFireChargeSysUserId());
                        qwUser.eq("platform", "cy");
                        qwUser.last("limit 1");
                        User user = userDao.selectOne(qwUser);
                        if(user != null){
                            fireWork.setLastSubmitWxUserId(user.getId());
                            fireWork.setLastCheckWxUserId(user.getId());
                        }
                    }
                }
                // 动火作业票
                else if(fireWork.getRecordType() == 0){
                    // 非生产   批准人  生产经理
                    //非生产
                    if(fireWork.getOpLevel() == 1){
                        fireWork.setLastSubmitSysUserId(shop.getFireChargeSysUserId());

                        SysUser sysUser = sysUserDao.selectById(shop.getFireChargeSysUserId());
                        if(sysUser != null){
                            fireWork.setLastSubmitUserName(sysUser.getName());

                            QueryWrapper<User> qwUser = new QueryWrapper<>();
                            qwUser.eq("sys_user_id", shop.getFireChargeSysUserId());
                            qwUser.eq("platform", "cy");
                            qwUser.last("limit 1");
                            User user = userDao.selectOne(qwUser);
                            if(user != null){
                                fireWork.setLastSubmitWxUserId(user.getId());
                            }
                        }
                    }
                    //生产
                    // 生产区域  批准人 要显示 片区经理
                    else if(fireWork.getOpLevel() == 2){
                        //最后批准人   片区管理员
                        QueryWrapper<SysUser> qwPianquUser = new QueryWrapper<>();
                        qwPianquUser.eq("pianqu_id", shop.getPianquId());
                        qwPianquUser.eq("user_type",3);
                        qwPianquUser.last("limit 1");
                        SysUser sysUser = sysUserDao.selectOne(qwPianquUser);
                        if(sysUser != null){
                            fireWork.setLastSubmitSysUserId(sysUser.getUserId().intValue());
                            fireWork.setLastSubmitUserName(sysUser.getName());

                            QueryWrapper<User> qwUser = new QueryWrapper<>();
                            qwUser.eq("sys_user_id", sysUser.getUserId());
                            qwUser.eq("platform", "cy");
                            qwUser.last("limit 1");
                            User user = userDao.selectOne(qwUser);
                            if(user != null){
                                fireWork.setLastSubmitWxUserId(user.getId());
                            }
                        }
                    }
                }

            }

            ret = fireWorkDao.insert(fireWork);
            if(ret<= 0){
                throw new TransactionalException("fireWorkDao insert error");
            }

            int workId = fireWork.getId();
            JSONArray outWorker = JSONUtil.parseArray(outWorkers);
            if(outWorker != null){
                if(outWorker.size() > 0){
                    List<FireWorkUser> outUsers = JSONUtil.toList(outWorkers,FireWorkUser.class);
                    for (FireWorkUser user : outUsers){
                        user.setFireWorkId(workId);
                        if(StringUtils.isEmpty(user.getWorkType())){
                            if(fireWork.getRecordType() == 0){
                                user.setWorkType("电焊工");
                            }else if(fireWork.getRecordType() == 2){
                                user.setWorkType("高空作业工");
                            }else if(fireWork.getRecordType() == 1){
                                user.setWorkType("有限空间工");
                            }else{
                                user.setWorkType("其他工种");
                            }
                        }
                        ret = fireWorkUseDao.insert(user);
                        if(ret <= 0){
                            throw new TransactionalException("fireWorkUseDao insert error");
                        }
                    }
                }
            }


            //督导员（安全员）
            List<String> innerWorkers = JSONUtil.toList(workerList,String.class);
            if(innerWorkers != null && innerWorkers.size() > 0){
                for (String sysId : innerWorkers){
                    SysUser sysUser = sysUserDao.selectById(Integer.parseInt(sysId));
                    if(sysUser != null){
                        FireWorkUser workUser = new FireWorkUser();
                        workUser.setFireWorkId(workId);
                        if(fireWork.getRecordType() == 0){
                            workUser.setWorkType("电焊工");
                        }else if(fireWork.getRecordType() == 2){
                            workUser.setWorkType("高空作业工");
                        }else if(fireWork.getRecordType() == 1){
                            workUser.setWorkType("有限空间工");
                        }else{
                            workUser.setWorkType("其他工种");
                        }
                        workUser.setWorkerSysUserId(Integer.parseInt(sysId));
                        workUser.setWorkerName(sysUser.getName());
                        workUser.setWorkCardNum(sysUser.getCertificateNum());
                        workUser.setIsOut(0);
                        ret = fireWorkUseDao.insert(workUser);
                        if(ret <= 0){
                            throw new TransactionalException("fireWorkUseDao insert error");
                        }

                        List<User> users = userService.getUserListBySysUserId(Integer.parseInt(sysId),"cy");
                        if(CollUtil.isNotEmpty(users)){
                            for (User user : users){
                                System.out.println("推送通知的焊工：" + user.getPhonenum() + " - " + sysUser.getName());
                                wxWorkerUserId.add(user.getId());
                            }
                        }
                    }
                }
            }

            List<FireSafetyMeasures> safetyMeasures = safetyMeasuresDao.selectListByColumn("measures_type",fireWork.getRecordType());
            if(CollUtil.isNotEmpty(safetyMeasures)){
                for (FireSafetyMeasures measure : safetyMeasures){
                    FireWorkMeasures workMeasures = new FireWorkMeasures();
                    workMeasures.setFireWorkId(workId);
                    workMeasures.setSafetyMeasures(measure.getMeasureTitle());
                    workMeasures.setMeasureId(measure.getId());
                    workMeasures.setState(0);
                    workMeasures.setIsInput(measure.getIsInput());
                    workMeasures.setOpType(measure.getOpType());
                    ret = fireWorkMeasuresDao.insert(workMeasures);
                    if(ret <= 0){
                        throw new TransactionalException("fireWorkMeasuresDao insert error");
                    }
                }
            }

            //发送短信推送通知
//            smsTemplateService.sendSmsByToFireWork(fireWork.getRegCompanyName() + " "+ fireWork.getRegUserName(),fireWork.getRecordType(),0);
//
//            //公众号推送（只推送给焊工，工作人员）
            wxTemplateService.sendWxMsgRegFireWork(fireWork, wxWorkerUserId);

        } catch (Exception e){
            e.printStackTrace();
        }
        return ret;
    }

    @Override
    public FireWork getFireWorkByState(Integer deviceId, Integer state) {
        return fireWorkDao.getFireWorkByState(deviceId,state);
    }

    @Override
    public List<FireWork> getFireWorkListBySysUserId(Map<String, Object> map, Integer offset, Integer pageSize) {
        return fireWorkDao.getFireWorkListBySysUserId(map,offset,pageSize);
    }
}
